/**
 *  ==== 自己动手实现 Promise ======
 */

const PENDING = 'PENDING' //默认是等待态
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'

class Promise {

  constructor(executor) {
    this.status = PENDING
    this.value = undefined;
    this.reason = undefined
    this.onResolvedCallbacks = []
    this.onRejectedCallbacks = []


    // 用户调用 resolve 和 rejected 可以将对应的结果保留在当前的 promise 实例上
    const resolve = (value) => {
      if (this.status == PENDING) {
        this.value = value;
        this.status = FULFILLED
        this.onResolvedCallbacks.forEach((fn) => fn())
      }
    }
    const reject = (reason) => {
      if (this.status == PENDING) {
        this.reason = reason
        this.status = REJECTED
        this.onRejectedCallbacks.forEach(fn => fn())
      }
    }

    try {
      executor(resolve, reject)// 默认 new Promise 中的 executor执行器会立即执行
    } catch (e) { // 如果执行时出错,我们将错误传递到 reject 中
      reject(e)
    }

  }


  then(onFulfilled, onRejected) {
    if (this.status == FULFILLED) {
      onFulfilled(this.value)
    }

    if (this.status == REJECTED) {
      onRejected(this.reason)
    }
    if (this.status == PENDING) {
      console.log("pending");
      // 发布订阅模式
      this.onResolvedCallbacks.push(() => {
        onFulfilled(this.value)
      })
      this.onRejectedCallbacks.push(() => {
        onRejected(this.reason)
      })
    }
  }

}

module.exports = Promise
